package zb.filter;

import zb.util.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class PowerFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("7004");
        //获取请求的地址
        String path = exchange.getRequest().getURI().getPath();
        System.out.println("请求的地址:"+path);
        //登录功能放行
        if(path.startsWith("/api/user/login")){
            //放行
            return chain.filter(exchange);
        }
        //不是登录，要求参数带token
        //获取第一个请求参数是token的值
        String token = exchange.getRequest().getQueryParams().getFirst("token");
        if(StringUtils.isEmpty(token)){
            //阻止继续访问
            System.out.println("没有token,阻止继续访问");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);//401
            return exchange.getResponse().setComplete();
        }

        //取出来，验证token
        try {
            JwtUtil.parseJWT(token);
            //没有问题，继续转发
            return chain.filter(exchange);
        } catch (Exception e) {
            e.printStackTrace();
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);//406
            return exchange.getResponse().setComplete();
        }
    }
    @Override
    public int getOrder() {
        return 0;
    }
}
